package com.st.shopadmin.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class CookieUtil {
    //private final static String COOKIE_DOMAIn=".myheartpengpeng.com";
    private final static String COOKIE_DOMAIn="dhp.s1.natapp.cc";//写在大一点级别的domain下边
    private final static String COOKIE_NAME="mymall_login_token";//服务器端种到客服端的
    private static final Logger logger = LoggerFactory.getLogger(JsonUtil.class);

    public static String readLoginToken(HttpServletRequest requst){
        Cookie[]  cks = requst.getCookies();
        if(cks != null){
            for(Cookie ck :cks){
                logger.info("read cookis name:{},cookis values:{}",ck.getName(),ck.getValue());
                if(StringUtils.equals(ck.getName(),COOKIE_NAME)){
                    logger.info("return cookiesname:{},cookies values :{}",ck.getName(),ck.getValue());
                    return ck.getValue();
                }
            }
        }
        return  null;

    }
    //X:domain=".myheartpengpeng.com"
    //a:A.myheartpengpeng.com           cookie:domain=A.myheartpengpeng.com;path="/"
    //b:B.myheartpengpeng.com           cookie:domain=B.myheartpengpeng.com;path="/"
    //c:A.myheartpengpeng.com/test/cc   cookie:domain=A.myheartpengpeng.com;path="/test/cc"
    //d:A.myheartpengpeng.com/test/dd   cookie:domain=A.myheartpengpeng.com;path="/test/dd"
    //e:A.myheartpengpeng.com/test      cookie:domain=A.myheartpengpeng.com;path="/test"
    public static  void  writeLoginToken(HttpServletResponse response,String token){
        Cookie ck = new Cookie(COOKIE_NAME,token);
        ck.setDomain(COOKIE_DOMAIn);
        ck.setPath("/");
        ck.setHttpOnly(true); //防止脚本攻击泄露信息 设置之后无法通过cookie获取信息
        //单位是秒
        //如果不设置MaxAge的话，cookie不会写入硬盘，而写在内存。只在当前页面有效
        ck.setMaxAge(60 * 60 * 24 * 365);//如果设置 -1代表永久有效
        logger.info("write cookiesname:{} cookiesValue:{}",ck.getName(),ck.getValue());
        response.addCookie(ck);
    }

    public static void delLoginToken(HttpServletRequest requst,HttpServletResponse response){
        Cookie[]  cks = requst.getCookies();
        if(cks != null){
            for(Cookie ck :cks){
                if(StringUtils.equals(ck.getName(),COOKIE_NAME)){
                    ck.setDomain(COOKIE_DOMAIn);
                    ck.setPath("/");
                    ck.setMaxAge(0);//设置0 代表删除cookies
                    logger.info(" del cookiesname;{},cookiesvalue:{]",ck.getName(),ck.getValue());
                    response.addCookie(ck);
                    return;
                }
            }
        }
    }
}
